import os
import aiohttp
import json

from goldenverba.components.interfaces import Generator


class CohereGenerator(Generator):
    """
    CohereGenerator Generator.
    """

    def __init__(self):
        super().__init__()
        self.name = "CommandR+"
        self.description = "Generator using Cohere's command-r-plus model"
        self.requires_env = ["COHERE_API_KEY"]
        self.streamable = True
        self.model = "command-r-plus"
        self.context_window = 10000
        self.url = "https://api.cohere.ai/v1/chat"

    async def generate_stream(
        self,
        queries: list[str],
        context: list[str],
        conversation: dict = None,
    ):
        """Generate a stream of response dicts based on a list of queries and list of contexts, and includes conversational context
        @parameter: queries : list[str] - List of queries
        @parameter: context : list[str] - List of contexts
        @parameter: conversation : dict - Conversational context
        @returns Iterator[dict] - Token response generated by the Generator in this format {system:TOKEN, finish_reason:stop or empty}.
        """

        if os.environ.get("COHERE_API_KEY") == None:
            yield {
                "message": "Missing Cohere API Key",
                "finish_reason": "stop",
            }

        

        if conversation is None:
            conversation = {}
        message, _conversation = self.prepare_messages(queries, context, conversation)

        data = {
            "model": self.model,
            "chat_history": _conversation,  # Assuming this structure from your context
            "message": message,
            "stream": True
        }

        headers = {
            'Authorization': f'Bearer {os.getenv("COHERE_API_KEY")}',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(self.url, json=data, headers=headers) as response:
                    if response.status == 200:
                            async for line in response.content:
                                if line.strip():
                                    json_data = json.loads(line.decode('utf-8'))
                                    message = json_data.get("text", "")
                                    finish_reason = "stop" if json_data.get("finish_reason", "") == "COMPLETE" else ""

                                    yield {
                                        "message": message,
                                        "finish_reason": finish_reason,
                                    }
                    else:
                        error_message = await response.text()
                        yield {
                            "message": f"HTTP Error {response.status}: {error_message}",
                            "finish_reason": "stop",
                        }

        except Exception as e:
            yield {
                "message": str(e),
                "finish_reason": "stop",
            }
            raise

    def prepare_messages(
        self, queries: list[str], context: list[str], conversation: dict[str, str]
    ) -> dict[str, str]:
        """
        Prepares a list of messages formatted for a Retrieval Augmented Generation chatbot system, including system instructions, previous conversation, and a new user query with context.

        @parameter queries: A list of strings representing the user queries to be answered.
        @parameter context: A list of strings representing the context information provided for the queries.
        @parameter conversation: A list of previous conversation messages that include the role and content.

        @returns A list of message dictionaries formatted for the chatbot. This includes an initial system message, the previous conversation messages, and the new user query encapsulated with the provided context.

        Each message in the list is a dictionary with 'role' and 'content' keys, where 'role' is either 'system' or 'user', and 'content' contains the relevant text. This will depend on the LLM used.
        """
        messages = [
            {
                "role": "CHATBOT",
                "message": "I am a Retrieval Augmented Generation chatbot. I'll answer user queries only with their provided context. If the provided documentation does not provide enough information, I say so. If the answer requires code examples I encapsulate them with ```programming-language-name ```. I don't do pseudo-code.",
            }
        ]

        for message in conversation:
            _type = ""
            _type = "CHATBOT" if message.type == "system" else "USER"

            messages.append({"role": _type, "message": message.content})

        query = " ".join(queries)
        user_context = " ".join(context)

        prompt = f"Please answer this query: '{query}' with this provided context: {user_context}"

        return prompt, messages
